import threading
import time
import cv2
import keyboard
from src import logic, predict, tool, keytool, win32
from py_base.window_base import *


class Gui(WinBase):
    def __init__(self):
        WinBase.__init__(self)

        self.setWindowTitle('bf_fly')

        self.addLabRow('窗口', QLineEdit(), 'winName')

        self.addGap()
        self.addLabRow('===== hsv =======', QLineEdit(), 'hsv')
        self.addLabRow('hsv_offset', QLineEdit(), 'offset')
        self.addLabRow('sv_offset', QLineEdit(), 'sv_offset')

        self.addGap()
        self.addLabRow('===== 分辨率预设 =======', QComboBox(), 'pxSet', func=self.changePxSet)
        self.pxSet.addItem("800*600")
        self.pxSet.addItem("1366*768")
        self.addLabRow('cutBox x1,x2,y1,y2', QLineEdit(), 'cutBox')
        self.addLabRow('shotBox x1,x2', QLineEdit(), 'shotBox')

        self.addGap()
        self.addLabRow('===== canny_offset =======', QLineEdit(), 'canny_offset')
        self.addLabRow('hfLine rho,pi,sum,minLength,maxLineGap', QLineEdit(), 'hfLine', func=self.hfLineChanged)
        self.addLabRow('动态明度 v_low，v_height#img_low，img_height v开头不生效', QLineEdit(), 'dynamicV')

        self.addGap()
        self.addLabRow('===== 自动平衡间隔，ms，0不处理 =======', QLineEdit(), 'balanceTimeGap', DTYPE_NUM)
        self.addLabRow('最小偏移阈值 %d px', self.createSlice(0, 30, 1), 'minGap')
        self.keyboardModel = self.addLabRow('键盘驱动', QComboBox(), 'keyboardModel')
        # self.keyboardModel.addItem("keyboard")
        self.keyboardModel.addItem("directinput")

        # self.addLabRow('键位 上,下,左,右', QLineEdit(), 'keyMap')
        self.info = self.addRow(QLabel(""))

        _, self.begin_btn = self.add2Btn('保存', '开始', self.set_setting, self.begin)
        self.keyboardTestBtn, self.checkPressBtn = self.add2Btn('按键测试', '是否按下', self.test_keyboard, self.checkPress)
        self.add2Btn('清除窗口', '清除窗口', self.clearWin, self.clearWin)

        self.addGap()
        self.createFilePicker('filePath')
        self.add2Btn('截图', '测试', self.imgCut, self.test)

        self.init_setting()
        self.setLayout(self.vbox)

    def clearWin(self):
        try:
            cv2.destroyAllWindows()
        except Exception as e:
            self.info.setText(str(e))

    def changePxSet(self, val):
        if not hasattr(self, 'cutBox'):
            return
        if val == "800*600":
            self.cutBox.setText("285,520,200,420")
            self.shotBox.setText("385,420")
        elif val == "1366*768":
            self.cutBox.setText("495,875,280,450")
            self.shotBox.setText("655,710")

    def imgCut(self):
        try:
            hwnd = win32.find_windows(enum.setting['winName'])
            if not hwnd:
                raise Exception("找不到窗口")
            image, hwnd = tool.get_screenshot(hwnd)
            cv2.imwrite('./img/' + time.strftime("%Y%m%d-%H%M%S") + '.jpg', image)
            self.info.setText('截图成功')

        except Exception as e:
            self.info.setText(str(e))

    def hfLineChanged(self, value):
        enum.setting['hfLine'] = value

    def checkPress(self):
        if enum.keypress_test:
            enum.keypress_test = False
            self.checkPressBtn.setText('是否按下')
        else:
            enum.keypress_test = True
            def dothink():
                while enum.keypress_test:
                    time.sleep(1)
                    print(keyboard.is_pressed('up'))

            self.checkPressBtn.setText('停止')
            threading.Thread(target=dothink).start()

    def test_keyboard(self):
        if enum.keyboard_test:
            enum.keyboard_test = False
            self.keyboardTestBtn.setText('按键测试')
        else:
            enum.keyboard_test = True
            def dothink():
                while enum.keyboard_test:
                    time.sleep(1)
                    keytool.press('up', 100)

            self.keyboardTestBtn.setText('停止')
            threading.Thread(target=dothink).start()


    def test(self):
        self.set_setting()
        if enum.setting['filePath'] == '':
            return
        img = cv2.imread(enum.setting['filePath'])
        logic.frame(img, 1)


    def begin(self):
        self.set_setting()
        self.set_predict(not enum.predicting)

    def set_predict(self, isOpen):
        if isOpen:
            enum.predicting = True
            self.begin_btn.setText("停止")
            threading.Thread(target=logic.begin).start()

        else:
            self.info.setText('启动')
            enum.predicting = False
            self.begin_btn.setText("开始")





